package com.sec.etech.process.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sec.etech.common.constant.DBConstant;
import com.sec.etech.process.mapper.SppOperationStepMapper;
import com.sec.etech.process.mapper.SppRelToolMapper;
import com.sec.etech.process.model.SppOperationStep;
import com.sec.etech.process.model.SppRelTool;
import com.sec.etech.process.model.SppRouteStep;
import com.sec.etech.sys.util.DbUtil;
import org.openbpm.base.core.id.IdUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SppRelToolService extends ServiceImpl<SppRelToolMapper, SppRelTool> {
    @Resource
    SppRouteStepService sppRouteStepService;
    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private SppOperationStepMapper sppOperationStepMapper;


    /**
     * 获取路线卡/工序卡 工步关联的工装
     *
     * @param targetId
     * @param targetType
     * @param stepId
     * @return
     */
    public List<SppRelTool> getRefToolList(Long targetId, Integer targetType, Long stepId) {
        return baseMapper.selectList(Wrappers.<SppRelTool>lambdaQuery()
                .eq(SppRelTool::getTargetId, targetId)
                .eq(SppRelTool::getTargetType, targetType)
                .eq(SppRelTool::getStepId, stepId)
                .eq(SppRelTool::getActive, 1)
                .orderByAsc(SppRelTool::getOrderby)
        );
    }


    /**
     * 获取路线卡/工序卡 工步关联的工装
     * 包含自备工装
     *
     * @param targetId
     * @param targetType
     * @param stepId
     * @return
     */
    public List<Map<String, Object>> getRefTools(Long targetId, Integer targetType, Long stepId) {
        String sql = "SELECT t1.toolingid as toolingId, t2.plantaskid," +
                "if(length(t2.num)>0,t2.num,t1.tooling_num) AS toolingNum, " +
                "if(length(t2.toolinginame)>0,t2.toolinginame,t1.tooling_name)  AS toolingName  " +
                "FROM spp_rel_tool t1 " +
                "LEFT JOIN proc_tooling t2 on t1.toolingid = t2.toolingid " +
                "WHERE t1.target_id = ?  AND t1.target_type = ? AND t1.step_id = ?  AND t1.active = 1 " +
                "ORDER BY t1.orderby ASC";
        return DbUtil.getJdbcTemplate(DBConstant.ETECH_SLAVE).queryForList(sql, targetId, targetType, stepId);
    }

    /**
     * 获取路线卡/工序卡 关联的工装
     * 包含专用和通用工装
     * 不包含自备工装
     *
     * @param targetIds
     * @param targetType
     * @return
     */
    public List<Map<String, Object>> getRefTools(List<Long> targetIds, Integer targetType) {
        String sql = "SELECT t1.toolingid as toolingId,t2.plantaskid, " +
                " if(length(t2.num)>0,t2.num,t1.tooling_num) AS toolingNum," +
                " if(length(t2.toolinginame)>0,t2.toolinginame,t1.tooling_name) AS toolingName," +
                " if(length(t3.plantasknum)>0,t3.plantasknum,t2.spp_component) AS componentnum " +
                " FROM spp_rel_tool t1 " +
                " LEFT JOIN proc_tooling t2 ON t1.toolingid = t2.toolingid " +
                " LEFT JOIN proj_plantask t3 on t3.plantaskid = t2.plantaskid " +
                " WHERE t1.target_id in({})  AND t1.target_type = {}  AND t1.active = 1 and t1.toolingid >0 " +
                " AND t1.tooling_num not like 'ZBZP-%' AND t1.tooling_num not like 'ZBGZ-%' " +
                " GROUP BY t2.toolingid ORDER BY t1.orderby ASC";
        return jdbcTemplate.queryForList(StrUtil.format(sql, CollUtil.join(targetIds, ","), targetType));
    }

    /**
     * 获取路线卡/工序卡 关联的自备工装
     *
     * @param targetIds
     * @param targetType
     * @return
     */
    public List<Map<String, Object>> getRefSelfTools(List<Long> targetIds, Integer targetType) {
        String sql = "SELECT t1.toolingid as toolingId,if(length(t2.num)>0,t2.num,t1.tooling_num) AS toolingNum," +
                " if(length(t2.toolinginame)>0,t2.toolinginame,t1.tooling_name) AS toolingName " +
                " FROM spp_rel_tool t1 LEFT JOIN proc_tooling t2 ON t1.toolingid = t2.toolingid " +
                " WHERE t1.target_id in({})  AND t1.target_type = {} AND t1.active = 1 and ISNULL(t1.toolingid) " +
                " GROUP BY t1.tooling_num ORDER BY t1.orderby ASC";
        return jdbcTemplate.queryForList(StrUtil.format(sql, CollUtil.join(targetIds, ","), targetType));
    }


    /**
     * 获取路线卡/工序卡 工步关联的工装
     *
     * @param targetId
     * @param targetType
     * @param stepId
     * @param jsonArray
     */
    public void updateRefTool(Long targetId, Integer targetType, Long stepId, JSONArray jsonArray) {
        String sppPlantaskid = "";
        String sql = "";
        if (targetType == 1) {
            sql = "select t1.plantaskid from proc_process t1 ,spp_route_rev t2 " +
                    " where t1.processid = t2.processid and t2.route_rev_id =" + targetId;
        } else if (targetType == 2) {
            sql = "select t1.plantaskid from proc_process t1 ,spp_operation_rev t2 " +
                    " where t1.processid = t2.processid and t2.op_rev_id =" + targetId;
        }
        List<String> list = CollUtil.newArrayList();
        if (StrUtil.isNotBlank(sql)) {
            list = jdbcTemplate.queryForList(sql, String.class);
            if (CollUtil.isNotEmpty(list)) {
                sppPlantaskid = list.get(0);
            }

        }
        List<String> toolIds = new ArrayList<>();
        List<String> toolingNames = new ArrayList<>();
        List<String> toolingNums = new ArrayList<>();
        for (Object o : jsonArray) {
            JSONObject jsonObject = JSONUtil.parseObj(o);
            //没有id的为自备工装
            if (StrUtil.isNotBlank(jsonObject.getStr("toolingId"))) {
                toolIds.add(jsonObject.getStr("toolingId"));
            } else {
                toolingNums.add(jsonObject.getStr("toolingNum"));
            }
            String plantaskid = jsonObject.getStr("plantaskid");
            if (StrUtil.isNotBlank(plantaskid) && sppPlantaskid.equals(plantaskid)) {
                toolingNames.add(jsonObject.getStr("toolingNum") + "\n" + jsonObject.getStr("toolingName"));
            } else if (StrUtil.isNotBlank(jsonObject.getStr("toolingId"))) {
                sql = "SELECT IF( length( t2.plantasknum ) > 0, t2.plantasknum, t1.spp_component ) AS componentnum " +
                        " FROM proc_tooling t1" +
                        " LEFT JOIN proj_plantask t2 ON t1.plantaskid = t2.plantaskid " +
                        " where t1.toolingid = " + jsonObject.getStr("toolingId");
                list = jdbcTemplate.queryForList(sql, String.class);
                if (CollUtil.isNotEmpty(list) && StrUtil.isNotBlank(list.get(0))) {
                    jsonObject.putOnce("componentnum", list.get(0));
                    toolingNames.add(StrUtil.format("{}\n{}\n({})", jsonObject.getStr("toolingNum"), jsonObject.getStr("toolingName"), list.get(0)));
                } else {
                    toolingNames.add(jsonObject.getStr("toolingNum") + "\n" + jsonObject.getStr("toolingName"));
                }
            } else {
                toolingNames.add(jsonObject.getStr("toolingNum") + "\n" + jsonObject.getStr("toolingName"));
            }
        }
        List<String> oldToolIds = new ArrayList<>();
        List<String> oldToolNums = new ArrayList<>();
        List<SppRelTool> updateList = getRefToolList(targetId, targetType, stepId);
        if (CollUtil.isNotEmpty(updateList)) {
            for (SppRelTool sppRelTool : updateList) {
                if (sppRelTool.getToolingId() != null) {
                    String toolingId = String.valueOf(sppRelTool.getToolingId());
                    oldToolIds.add(toolingId);
                    int index = toolIds.indexOf(toolingId);
                    if (index > -1) {
                        JSONObject jsonObject = JSONUtil.parseObj(jsonArray.get(index));
                        sppRelTool.setOrderby(jsonObject.getInt("orderby"));
                    } else {
                        sppRelTool.setActive(0);
                    }
                } else {
                    String toolingNum = String.valueOf(sppRelTool.getToolingNum());
                    oldToolNums.add(toolingNum);
                    int index = toolingNums.indexOf(toolingNum);
                    if (index > -1) {
                        JSONObject jsonObject = JSONUtil.parseObj(jsonArray.get(index));
                        sppRelTool.setOrderby(jsonObject.getInt("orderby"));
                    } else {
                        sppRelTool.setActive(0);
                    }
                }
            }
            this.updateBatchById(updateList);
        }
        List<SppRelTool> addList = new ArrayList<>();
        for (Object o : jsonArray) {
            JSONObject jsonObject = JSONUtil.parseObj(o);
            String toolingId = jsonObject.getStr("toolingId");
            String toolingNum = jsonObject.getStr("toolingNum");
            String toolingName = jsonObject.getStr("toolingName");
            Integer orderby = jsonObject.getInt("orderby");
            boolean isadd = false;
            if (StrUtil.isNotBlank(toolingId)) {
                if (oldToolIds.indexOf(toolingId) == -1) {
                    isadd = true;
                }
            } else if (StrUtil.isNotBlank(toolingNum)) {
                if (oldToolNums.indexOf(toolingNum) == -1) {
                    isadd = true;
                }
            }
            if (isadd) {
                SppRelTool sppRelTool = new SppRelTool();
                sppRelTool.setRelToolId(IdUtil.getUId());
                sppRelTool.setTargetId(targetId);
                sppRelTool.setTargetType(targetType);
                sppRelTool.setStepId(stepId);
                if (StrUtil.isNotBlank(toolingId)) {
                    sppRelTool.setToolingId(Long.valueOf(toolingId));
                }
                sppRelTool.setToolingNum(toolingNum);
                sppRelTool.setToolingName(toolingName);
                if (orderby != null) {
                    sppRelTool.setOrderby(orderby);
                } else {
                    sppRelTool.setOrderby(jsonArray.indexOf(o) + 1);
                }
                sppRelTool.setActive(1);
                addList.add(sppRelTool);
            }
        }
        if (CollUtil.isNotEmpty(addList)) {
            this.saveBatch(addList);
        }

        if (targetType == 1) {
            SppRouteStep sppRouteStep = sppRouteStepService.getById(stepId);
            if (sppRouteStep != null) {
                sppRouteStep.setToolings(CollUtil.isNotEmpty(toolingNames) ? CollUtil.join(toolingNames, "\n") : "");
                sppRouteStepService.updateById(sppRouteStep);
            }
        } else if (targetType == 2) {
            SppOperationStep sppOperationStep = sppOperationStepMapper.selectById(stepId);
            if (sppOperationStep != null) {
                sppOperationStep.setToolings(CollUtil.isNotEmpty(toolingNames) ? CollUtil.join(toolingNames, "\n") : "");
                sppOperationStepMapper.updateById(sppOperationStep);
            }
        }
    }
}
